﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static SY_Library.User32;

namespace ShortcutMenu.Hooks
{
    public class ViewDisplayHook : HookBase
    {
        public const int WM_KEYDOWN = 0x0100;
        public const int WH_KEYBOARD_LL = 13;
        public const int WM_SYSKEYDOWN = 0x0104;
        //钩子回掉委托实例
        private static HookHandlerDelegate proc;
        //钩子句柄
        private static IntPtr hKeyboardHook;
        //绑定触发函数
        Action Action;

        static bool judge = false;

        public ViewDisplayHook(MainWindow mainWindow) : base(mainWindow)
        { }

        public int HookCallback(int nCode, IntPtr wparam, ref KBDLLHOOKSTRUCT lparam)
        {
            if (
                nCode >= 0
                &&
                (wparam == (IntPtr)WM_KEYDOWN
                ||
                wparam == (IntPtr)WM_SYSKEYDOWN)
                )
            {
                if (judge && lparam.vkCode == 165)
                {
                    Action();
                }
                if (lparam.vkCode == 163)
                {
                    judge = true;
                }
                else
                {
                    judge = false;
                }
            }
            return 0;
        }

        public override void HookStart(Action action)
        {
            if (hKeyboardHook == IntPtr.Zero)
            {
                // 创建HookProc实例 
                proc = new HookHandlerDelegate(HookCallback);
                using (Process curPro = Process.GetCurrentProcess())
                using (ProcessModule curMod = curPro.MainModule)
                {
                    //定义全局钩子 
                    hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, proc, SY_Library.Kernel32.GetModuleHandle(curMod.FileName), 0);
                    this.Action = action;
                }

                if (hKeyboardHook == IntPtr.Zero)
                {
                    HookStop();
                    throw new Exception("钩子设置失败");
                }
            }

        }

        public override void HookStop()
        {
            bool retKeyboard = true;
            if (hKeyboardHook != IntPtr.Zero)
            {
                retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
                hKeyboardHook = IntPtr.Zero;
            }
            if (!(retKeyboard)) throw new Exception("卸载钩子失败");

        }
    }
}
